package com.xiaofeng.springboot.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xiaofeng.springboot.domain.dao.UserDao;
import com.xiaofeng.springboot.domain.entity.UserEntity;
import com.xiaofeng.springboot.dto.UserSearchDto;
import com.xiaofeng.springboot.service.UserService;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * 用户服务实现类
 * @author chenzf
 *
 */
@SuppressWarnings("static-method")
@Service
@CacheConfig(cacheNames = "user")
public class UserServiceImpl implements UserService {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private UserDao userDao;

	@Override
	@Transactional(rollbackFor = Exception.class)
	//使用参数#p代替(如：参数1#p0参数2#p1) 或者使用参数名#user
	//@CachePut(key = "#p0.id")
	@CachePut(key = "#user.id")
	public UserEntity save(UserEntity user) {
		Long id = user.getId();
		if (id == null) {
			userDao.insert(user);
		} else {
			userDao.updateByPrimaryKeySelective(user);
		}
		//		if (user != null) {
		//			throw new RuntimeException("测试事物");
		//		}
		return user;
	}

	@Override
	public List<UserEntity> findAll(UserSearchDto user) {
		Example example = new Example(UserEntity.class);
		String orderBy = user.getOrderBy();
		if (StringUtils.isNotBlank(orderBy)) {
			example.setOrderByClause(orderBy);
		}
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("mobile", user.getMobile());
		String username = user.getUsername();
		if (StringUtils.isNotBlank(username)) {
			criteria.andLike("username", "%" + username + "%");
		}
		criteria.andEqualTo("status", user.getStatus());
		String lastModifyBy = user.getLastModifyBy();
		if (StringUtils.isNotBlank(lastModifyBy)) {
			criteria.andLike("lastModifyBy", "%" + lastModifyBy + "%");
		}
		String beginTime = user.getBeginTime();
		String overTime = user.getOverTime();
		if (StringUtils.isNotBlank(beginTime) || StringUtils.isNotBlank(overTime)) {
			Date begin = transformTime(beginTime);
			Date over = transformTime(overTime);
			if (over != null && begin != null) {
				criteria.andBetween("lastModifyTime", begin, over);
			} else {
				criteria.andGreaterThanOrEqualTo("lastModifyTime", begin);
				criteria.andLessThanOrEqualTo("lastModifyTime", over);
			}
		}
		return userDao.selectByExample(example);
		//				Path<String> username = root.get("username");
		//				Path<String> mobile = root.get("mobile");
		//				Path<Integer> status = root.get("status");
		//				Path<Date> lastModifyTime = root.get("lastModifyTime");
		//				Path<String> lastModifyBy = root.get("lastModifyBy");
		//
		//				if (StringUtils.isNotBlank(dto.getUserName())) {
		//					where.add(cb.and(cb.like(username, "%" + dto.getUserName() + "%")));
		//				}
		//				if (StringUtils.isNotBlank(dto.getMobile())) {
		//					where.add(cb.and(cb.like(mobile, dto.getMobile())));
		//				}
		//				if (dto.getStatus() != null) {
		//					where.add(cb.and(cb.equal(status, dto.getStatus())));
		//				}
		//				if (StringUtils.isNotBlank(dto.getTimeBegin()) || StringUtils.isNotBlank(dto.getTimeOver())) {
		//					Date timeBegin = transformTime(dto.getTimeBegin());
		//					Date timeOver = transformTime(dto.getTimeOver());
		//					if (timeOver != null && timeBegin != null) {
		//						where.add(cb.and(cb.between(lastModifyTime, timeBegin, timeOver)));
		//					} else if (timeBegin != null) {
		//						where.add(cb.and(cb.greaterThanOrEqualTo(lastModifyTime, timeBegin)));
		//					} else if (timeOver != null) {
		//						where.add(cb.and(cb.lessThanOrEqualTo(lastModifyTime, timeOver)));
		//					}
		//				}
		//				if (StringUtils.isNotBlank(dto.getLastModifyBy())) {
		//					where.add(cb.like(lastModifyBy, "%" + dto.getLastModifyBy() + "%"));
		//				}
	}

	public Date transformTime(String time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//小写的mm表示的是分钟  
		Date date = null;
		try {
			date = sdf.parse(time);
		} catch (ParseException e) {
			logger.error("用户搜索时间格式转换出错, time={} , exception={} ", time, e);
			date = null;
		}
		return date;
	}

	@Override
	//使用参数#p代替(如：参数1#p0参数2#p1) 或者使用参数名#userId
	//@Cacheable(key = "#p0")
	@Cacheable(key = "#userId")
	public UserEntity getUser(Long userId) {
		return userDao.selectByPrimaryKey(userId);
	}

	@Override
	public UserEntity getUser(String loginNameOrMobile) {
		UserEntity userEntity = new UserEntity();
		if (isMobile(loginNameOrMobile)) {
			userEntity.setMobile(loginNameOrMobile);
			return userDao.selectOne(userEntity);
		}
		Example example = new Example(UserEntity.class);
		Criteria criteria = example.createCriteria();
		criteria.orEqualTo("loginName", loginNameOrMobile);
		criteria.orEqualTo("mobile", loginNameOrMobile);
		List<UserEntity> users = userDao.selectByExample(example);
		if (CollectionUtils.isEmpty(users)) {
			return null;
		}
		return users.get(0);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteUser(Long userId) {
		userDao.deleteByPrimaryKey(userId);
	}

	/**
	 * 验证手机号码
	 * @param param
	 * @return
	 */
	private boolean isMobile(String param) {
		try {
			Long.valueOf(param.trim());
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public UserEntity getUserInfo(String loginName) {
		return userDao.findByLoginName(loginName);
	}
}
